<?php defined('SYSPATH') or die('No direct script access.');

class Model_Shop_Review_Otzovik extends Model_Shop_Review_Abstract
{ 
    protected $_table_name = 'shop_otzovik_reviews';  
    
    public function get_entity()
    {
        return 'otzovik';
    }
    
    public function get_reviews_query(Model_Shop $shop)
    {
        return DB::select(
                array(DB::expr('\'otzovik\''), 'entity'),
                'id',
                'shop_id',
                'source_id',
                'user_nick',
                'user_link',
                'rating',
                array(DB::expr('NULL'), 'experience'), 
                'pluses',
                'minuses',
                'text',
                'link',
                'date',
                'usefulness',
                'u_yes',
                'u_no',
                array(DB::expr('\'0\''), 'trim')
            )
            ->from($this->_table_name)
            ->where('shop_id', '=', $shop->id);
    }
    
    public function add_review(Model_Shop $shop, $source_id, $text, $pluses, $minuses, $rating,
        $user_nick, $user_link, $link, $date, $u_yes, $u_no, $rank)
    {
        $this->shop_id  = $shop->id;
        $this->source_id = $source_id;
        $this->text     = $text;
        $this->pluses   = $pluses;
        $this->minuses  = $minuses;
        $this->rating   = $rating;
        $this->user_nick = $user_nick;
        $this->user_link = $user_link;
        $this->link     = $link;
        $this->date     = $date;
        $this->u_yes    = $u_yes;
        $this->u_no     = $u_no;
        //$this->usefulness = $this->get_usefulness();
		$this->usefulness = 10000-$rank;
		
		try {
			$this->save();
			
			$shop->change_count_reviews();
			if ($rating) {
				$shop->change_count_stars($rating);
			}
		} catch (Database_Exception $e) {
			if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
				return null;
			}
			die($e->getMessage());
		}
        
        return $this;  
    }    
}